package com.ifast.websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;


//@ServerEndpoint("/websocket")
@ServerEndpoint("/hessian/websocket/{sid}")
@Component
@Slf4j
public class OldWebSocketServer {
	 
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String,OldWebSocketServer> webSocketSet = new ConcurrentHashMap<String,OldWebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid="1";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
    	 
    	session.setMaxIdleTimeout(3600000);
        this.session = session; 
        webSocketSet.put(sid,this);     //加入set中
        addOnlineCount();         //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
        	 sendMessage("HEART_BEAT");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this.sid);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
    	
    	if(StringUtils.isBlank(message)) return ;
    	
    	if("HEART_BEAT".equals(message)){
    		log.info("收到来自窗口"+sid+"的心跳检测");
    		try {
				session.getBasicRemote().sendText("HEART_BEAT");
			} catch (IOException e) { 
				e.printStackTrace();
			}
    		return ;
    	}
    	log.info("收到来自窗口"+sid+"的信息:"+message);
        //群发消息
        for (OldWebSocketServer item : webSocketSet.values()) {
            try{
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

	/**
	 * 
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
	/**
	 * 实现服务器主动推送
	 */
    public void sendMessage(String message) throws IOException { 
    	if(this.session.isOpen())
        this.session.getBasicRemote().sendText(message);
    } 
    
    private void sendByteBuffer(ByteBuffer buf){
    	if(!this.session.isOpen()) return ; 
    	 try {
			this.session.getBasicRemote().sendBinary(buf);
		} catch (IOException e) { 
			e.printStackTrace();
		} 
	}
 
    /**
     * 群发自定义消息
     * */
    public static synchronized void sendByteBuffer(ByteBuffer buf,@PathParam("sid") String sid){
    	
    	//log.info("推送消息到窗口"+sid+"，推送内容图片"); 
    	if(webSocketSet.keySet().contains(sid)){ 
    		webSocketSet.get(sid).sendByteBuffer(buf); 
    	}  
    }
    public static boolean canSend(String sid){
    	if(webSocketSet.keySet().contains(sid)){ 
    		return false;
    	} 
    	return true;
    }
    
    /**
     * 群发自定义消息
     * */
    public static synchronized void sendInfo(String message,@PathParam("sid") String sid){
    	
    	//log.info("推送消息到窗口"+sid+"，推送内容:"+message);
    	
    	if(webSocketSet.keySet().contains(sid)){ 
    		try {
				webSocketSet.get(sid).sendMessage(message);
			} catch (IOException e) { 
				e.printStackTrace();
			} 
    	}else{
    		
    		for(OldWebSocketServer item : webSocketSet.values()){
                try {
                	//这里可以设定只推送给这个sid的，为null则全部推送
                	item.sendMessage(message);
                	
                } catch (IOException e){
                    continue;
                }
            }
    	} 
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        OldWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        OldWebSocketServer.onlineCount--;
    }
}
